package servletAction;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.context.ApplicationContext;

import util.DomainUtils;
import util.FormArgumentsException;
import actionForm.ActionGroupDispatcherValidationForm;
import actionForm.AddContactGroupValidationForm;
import domain.dao.interfaces.IDAOContactGroup;
import domain.entities.interfaces.IUser;

public class AddContactGroupAction extends Action{

	public ActionForward execute(final ActionMapping pMapping,
			ActionForm pForm, final HttpServletRequest pRequest,
			final HttpServletResponse pResponse) {

		final AddContactGroupValidationForm lForm = (AddContactGroupValidationForm) pForm;

		String group_name = lForm.getGroup_name();
		String[] contacts_of_group = lForm.getContacts_of_group();

		ApplicationContext context = util.SpringUtils.getApplicationContext();

		try {
			
			IDAOContactGroup daoContactGroup = (IDAOContactGroup) context.getBean("beanDAOContactGroup");
			daoContactGroup.addContactGroup(
					
					((IUser)pRequest.getSession(false).getAttribute(DomainUtils.CURRENT_USER_STRING)).getId(),
					group_name,
					contacts_of_group);

			DomainUtils.displayInfoMessage(
					pRequest, 
					DomainUtils.ADD_CONTACT_GROUP_ALERT_CURRENT_COLOR, 
					"Contact group created successfully.");
		}
		catch(Exception e) {

			if((e instanceof FormArgumentsException) == false) {
				pRequest.setAttribute(DomainUtils.ALERT_ERROR_STRING, "An error occur on the server.");
				System.err.println(e);
			}

			DomainUtils.keepParametersContent(pRequest);
		}


		return pMapping.findForward("stay");
		
	}
	
}
